package zpf.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import zpf.entity.User;

/**
 * @ClassName: MovieRibbonHystrixController
 * @Description: Web控制器测试断路器功能
 * @Autor: ZPF
 * @Date: 2021/1/13 11:22
 **/
@RestController
public class MovieRibbonHystrixController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/movie/{id}")
//    @HystrixCommand(fallbackMethod = "findByIdFallback")
    @HystrixCommand(
            fallbackMethod = "findByIdFallback",
            commandKey = "findById",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"),
                    @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "6")
            })
    public User findById(@PathVariable Long id) {
        System.out.println("== findById " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());

        return this.restTemplate.getForObject("http://provider-user/simple/" + id, User.class);
    }

    /**
     * 当 provider-user 服务宕机或者不可用时，即请求超时后会调用此方法。
     */
    public User findByIdFallback(Long id) {
        System.out.println("== findByIdFallback " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());

        User user = new User();
        user.setId(0L);
        return user;
    }

}
